package com.FindMyStuff.Activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.DigitsKeyListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.FindMyStuff.Model.DataAccessor;
import com.FindMyStuff.Model.DataBaseHelper;
import com.FindMyStuff.Model.InputChecker;
import com.FindMyStuff.Model.Item;
import com.FindMyStuff.Model.ItemCategory;
import com.FindMyStuff.Model.ItemType;
import com.FindMyStuff.Model.SessionManager;

public class AddItemActivity extends Activity {
	
	/**
	 * Holds the SessionManager so garbage collection will not get rid of the session manager
	 */
	private SessionManager sm;
	/**
	 * Stores input from user
	 */
	private String name;
	/**
	 * Stores input from user
	 */
	private String location;
	/**
	 * Stores input from user
	 */
	private String description;
	/**
	 * Stores input from user
	 */
	private String reward;
	/**
	 * Stores error information if the input from the user is bad
	 */
	private String error;
	/**
	 * Stored which item type the user selected
	 */
	private ItemType itemType;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sm = SessionManager.getInstance();
		
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setDisplayShowTitleEnabled(false);
		getActionBar().setIcon(getResources().getIdentifier("ic_home", "drawable",  getPackageName()));
		
		//EditText descrption = (EditText) findViewById(R.id.editText3);
		//descrption.setMovementMethod(new ScrollingMovementMethod());
		
		setContentView(R.layout.activity_add_item);
		Spinner spinner = (Spinner) findViewById(R.id.item_category);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
		        R.array.item_category, android.R.layout.simple_spinner_item);
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		
		Spinner spinner2 = (Spinner) findViewById(R.id.lostorfound);
		ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,
		        R.array.lost_or_found, android.R.layout.simple_spinner_item); //change this R.array
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner2.setAdapter(adapter2);
		spinner2.setOnItemSelectedListener(new SpinnerListener());
		
		EditText reward = (EditText)findViewById(R.id.editText4);
		String digits = "0123456789.";
	    reward.setKeyListener(DigitsKeyListener.getInstance(digits));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_add_item, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent toHome = new Intent(this, HomeActivity.class);
			startActivity(toHome);
			overridePendingTransition  (R.anim.left_slide_out, R.anim.left_slide_in);
			return true;
		case R.id.menu_logout:
			Intent intent = new Intent(this, LogInActivity.class);
			sm.logout();
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/**
	 * Checks the values in the editboxes of the Activity and then moves to the useritem's activity if the values are okay
	 * @param view
	 */
	public void createItem(View view){
		Intent intent = new Intent(this, UserItemsActivity.class);
		
		EditText itemName = (EditText) findViewById(R.id.editText1);
		EditText itemLocation = (EditText) findViewById(R.id.editText2);
		EditText itemDescription = (EditText) findViewById(R.id.editText3);
		EditText itemReward = (EditText) findViewById(R.id.editText4);
		Spinner item_category = (Spinner) findViewById(R.id.item_category);
		Spinner lost_or_found = (Spinner) findViewById(R.id.lostorfound);
		
		name = itemName.getText().toString();
		location = itemLocation.getText().toString();
		description = itemDescription.getText().toString();
		reward = itemReward.getText().toString();
		itemType = ItemType.convertStringToType(lost_or_found.getSelectedItem().toString());
		error = InputChecker.simpleCheckOnInputs(reward, itemType, name, location, description);
		if(!InputChecker.checkReward(reward) && itemReward.getVisibility()==EditText.VISIBLE){
			
		}
		if(!error.equals("") || (!InputChecker.checkReward(reward) && itemReward.getVisibility()==EditText.VISIBLE))
		{
			Dialog dialog = createBadInputDialog(error);
			dialog.show();
			
		} else 
		{
			Double reward = null;
			if(lost_or_found.getSelectedItem().toString().equals("Lost")){
				reward = Double.parseDouble(itemReward.getText().toString());
			}
			
			ItemCategory category = ItemCategory.convertStringtoCategory(item_category.getSelectedItem().toString());
			
			DataBaseHelper dbh = new DataBaseHelper(this);
			DataAccessor da = new DataAccessor(dbh);
			Item createdItem = null;
			Item matched;
			if(itemType.equals(ItemType.Lost)){
				createdItem = da.createItem(name, description, location, category, reward, ItemType.Lost);
				intent.putExtra("Text", "l");
				matched = da.getItemByNameAndLocation(createdItem.name, createdItem.location, ItemType.Found);
			}
			else{ 
				createdItem = da.createItem(name, description, location, category, (double)0, ItemType.Found);
				intent.putExtra("Text", "f");
				matched = da.getItemByNameAndLocation(createdItem.name, createdItem.location, ItemType.Lost);
			}
			if(!createdItem.exist())
			{
				System.out.println("Database DID NOT CREATE ITEM!!!");
			} else 
			{
				if(matched.exist())
				{
					intent.putExtra("item", "yes");
					sm.matchedItem = matched;
				}
				startActivity(intent);
			}
		}
	}
	
	/**
	 * Creates a dialog to tell the user the inputed data is incorrect
	 * @param error message to display to user
	 * @return dialog to show user
	 */
	public Dialog createBadInputDialog(String error) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);

	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    builder.setMessage(error);
	    builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
	               @Override
	               public void onClick(DialogInterface dialog, int id) {
	                   
	               }
	           });
	    return builder.create();
	}

	/**
	 * Takes the user back to the Home Activity
	 * @param view
	 */
	public void cancel(View view)
	{
		Intent intent = new Intent(this, HomeActivity.class);
		startActivity(intent);
		overridePendingTransition  (R.anim.left_slide_out, R.anim.left_slide_in);
	}
	
	/**
	 * 
	 * Private SpinnerListener implementation to hide the reward edittext based on the itemtype spinner
	 *
	 */
	private class SpinnerListener implements OnItemSelectedListener{

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			EditText itemReward = (EditText) findViewById(R.id.editText4);
			Spinner lost_or_found = (Spinner) findViewById(R.id.lostorfound);
			if(lost_or_found.getSelectedItem().toString().equals("Lost")){
				itemReward.setVisibility(View.VISIBLE);
			}
			else{
				itemReward.setVisibility(View.INVISIBLE);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
		
	}
}
